package controller;

import java.awt.Point;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import model.Model;
import model.pieces.Piece;

/**
 * Class implements a computer player that chooses a piece and its move randomly
 */
public class RandomMoves implements ComputerPlayer {

	// members
	private Model gameManager;
	private Random randomGenerator;
	
	// public methods
	
	/**
	 * Gets a reference to the board manager and an object to generate random numbers 
	 * @param boardManager- board manager
	 * @param randomGenerator- generates random numbers
	 */
	public RandomMoves(Model boardManager, Random randomGenerator) {
		
		// set members according to given values
		this.gameManager = boardManager;
		this.randomGenerator = randomGenerator;
	}
	
	/**
	 * According to currently playing player, randomly chooses a piece.
	 * The chosen piece's position is returned
	 */
	@Override
	public Point getPieceComputer(boolean isFirstPlayerTurn) {

		// get pieces of indicated player
		Map<Point, Piece> playerPieces = null;
		if (isFirstPlayerTurn) {			
			playerPieces = gameManager.getFirstPlayerPieces();
		} else {
			playerPieces = gameManager.getSecondPlayerPieces();
		}
		
		// choose randomly a piece from indicated player's map
		int pieceIndex = randomGenerator.nextInt(playerPieces.size());
		
		// iterate over map's keys
		Iterator<Point> iter = playerPieces.keySet().iterator();
		for (int i = 0 ; i < pieceIndex-1 ; ++i) {
			// proceed to next key
			iter.next();
		}
		
		// return piece position
		return iter.next();
	}

	/**
	 * Randomly chooses a move from given collection of piece's reachable positions.
	 * Returns the position to move to
	 */
	@Override
	public Point getMoveComputer(List<Point> moves) {
		
		// choose randomly an index in move list
		int moveIndex = randomGenerator.nextInt(moves.size());
		
		// return given move
		return moves.get(moveIndex);		
	}
}